package css.sword.util;


import org.apache.commons.codec.binary.Hex;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author zhuxiaomeng
 * @date 2017/12/7.
 * @email 154040976@qq.com
 * 采用md5加密 确保数据安全性
 */
public class Md5Util {

    /**
     * 对一个文件求他的md5值
     * @param  要求md5值的文件
     * @return md5串
     */
    public static String md5(InputStream fis) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[8192];
            int length;
            int sumLength=0;
            while ((length = fis.read(buffer)) != -1) {
                md.update(buffer, 0, length);
                sumLength+=length;
                if(sumLength==15*1024*1024) {
                    break;
                }
            }
            return new String(Hex.encodeHex(md.digest()));

        }  catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) fis.close();
                md.reset();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
}